package com.jing.yao.security.handler;

import com.jing.yao.bean.ResponseBean;
import com.jing.yao.cache.CacheHelper;
import com.jing.yao.code.UserCode;
import com.jing.yao.component.constants.BmsConstants;
import com.jing.yao.i18.MessageSourceHolder;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录成功
 *
 * @author lirui
 * @since 2020-06-24
 */
public class YaoLoginFailureHandler implements AuthenticationFailureHandler {

    @Autowired
    private CacheHelper cacheHelper;
    @Autowired
    private MessageSourceHolder messageSourceHolder;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setCharacterEncoding(BmsConstants.UTF_8);
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        String code = UserCode.USER_TOKEN_EXPIRED;
        if (exception instanceof BadCredentialsException) {
            code = UserCode.USER_PASSWORD_ERROR;
        }
        if (exception instanceof LockedException) {
            code = UserCode.USER_LOCKED;
        }
        ResponseBean responseBean = ResponseBean.builder().code(code).build();
        responseBean.setMessage(messageSourceHolder.getMessage(code));
        response.getWriter().print(new ObjectMapper().writeValueAsString(responseBean));
    }
}
